using UnityEngine;
using UnityEngine.SceneManagement;

public class LevelManager : MonoBehaviour
{
    public static LevelManager Instance { get; private set; }

    [SerializeField] GameData gameData;
    [SerializeField] Map[] maps;

    [SerializeField] GameObject gameObjectMaps;
    [SerializeField] GameObject gameObjectLevels;
    [SerializeField] GameObject gameObjectBack;

    private GameObject prefabLevel;

    void Awake()
    {
        Instance = this;
        this.prefabLevel = Resources.Load<GameObject>("Prefabs/Level/Level");
        this.ShowMaps();
    }

    void Start()
    {
        var mapData = this.gameData.mapData;

        for (int i = 0; i < maps.Length; i++)
        {
            maps[i].Show(i, mapData[i].starCount);
        }

        if (this.gameData.fromGame)
        {
            this.gameData.fromGame = false;
            LoadLevels(this.gameData.currentMapID);
            this.ShowLevels();
        }
    }

    void Update()
    {
        SystemSetting.Quit();
    }

    public void LoadLevels(int mapID)
    {
        var levels = this.gameData.mapData[mapID].levelData;
        var scrollViewContent = this.gameObjectLevels.transform.Find("Viewport").Find("Content");
        Common.ClearChildren(scrollViewContent);

        for (int j = 0; j < levels.Length; j++)
        {
            var level = Instantiate(this.prefabLevel);
            level.GetComponent<RectTransform>().SetParent(scrollViewContent);
            level.GetComponent<Level>().Show(j, levels[j].starCount, mapID);
        }

        this.ShowLevels();
    }

    public void ShowMaps()
    {
        this.gameObjectMaps.SetActive(true);
        this.gameObjectLevels.SetActive(false);
        this.gameObjectBack.SetActive(false);
    }

    public void ShowLevels()
    {
        this.gameObjectMaps.SetActive(false);
        this.gameObjectLevels.SetActive(true);
        this.gameObjectBack.SetActive(true);
    }

    public void LoadGame(int mapID, int levelID)
    {
        this.gameData.currentMapID = mapID;
        this.gameData.currentLevelID = levelID;
        SceneManager.LoadScene(nameof(Defines.GameScene));
    }
    
    public void OnBackClick()
    {
        this.ShowMaps();
    }
}
